#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>

#define PORT 8080
#define BUFFER_SIZE 1024
#define HTML_FILE "index.html"  // 静态页面文件

// 读取静态HTML文件内容
char* read_html_file() {
    FILE* file = fopen(HTML_FILE, "r");
    if (!file) {
        perror("Failed to open HTML file");
        return NULL;
    }

    fseek(file, 0, SEEK_END);
    long fsize = ftell(file);
    fseek(file, 0, SEEK_SET);

    char* content = (char*)malloc(fsize + 1);
    if (!content) {
        perror("Memory allocation failed");
        fclose(file);
        return NULL;
    }

    fread(content, 1, fsize, file);
    fclose(file);
    content[fsize] = '\0';
    return content;
}

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[BUFFER_SIZE] = {0};

    // 创建 socket 文件描述符
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置 socket 选项（允许地址重用）
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    // 绑定 socket 到端口
    if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d...\n", PORT);

    while (1) {
        // 接受客户端连接
        if ((new_socket = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept");
            exit(EXIT_FAILURE);
        }

        // 读取客户端请求
        ssize_t valread = read(new_socket, buffer, BUFFER_SIZE);
        printf("Received request:\n%s\n", buffer);

        // 解析HTTP GET请求（简化处理，仅支持根路径）
        char request_method[10], request_path[100];
        sscanf(buffer, "%s %s", request_method, request_path);

        // 构建HTTP响应
        char* html_content = read_html_file();
        if (!html_content) {
            const char* error_response = "HTTP/1.1 500 Internal Server Error\r\n\r\nInternal Server Error";
            send(new_socket, error_response, strlen(error_response), 0);
        } else {
            char response[BUFFER_SIZE];
            sprintf(response, "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: %lu\r\n\r\n%s",
                    strlen(html_content), html_content);
            send(new_socket, response, strlen(response), 0);
            free(html_content);
        }

        // 关闭连接
        close(new_socket);
    }
    close(server_fd);
    return 0;
}